const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs-extra');
const ImageProcessor = require('./imageProcessor');

let mainWindow;
const imageProcessor = new ImageProcessor();

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    frame: false,
    autoHideMenuBar: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    },
    icon: path.join(__dirname, '../assets/icon.png'),
    title: '图片批量处理工具'
  });

  mainWindow.loadFile('src/index.html');

  // 开发模式下打开开发者工具
  if (process.argv.includes('--dev')) {
    mainWindow.webContents.openDevTools();
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

// 禁用GPU加速以避免GPU相关错误
app.disableHardwareAcceleration();

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// IPC 事件处理

// 选择文件夹
ipcMain.handle('select-folder', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  });
  
  if (!result.canceled && result.filePaths.length > 0) {
    const folderPath = result.filePaths[0];
    const imageFiles = await getImageFilesFromFolder(folderPath);
    return { folderPath, imageFiles };
  }
  
  return null;
});

// 选择文件
ipcMain.handle('select-files', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openFile', 'multiSelections'],
    filters: [
      {
        name: '图片文件',
        extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp', 'svg', 'ico']
      }
    ]
  });
  
  if (!result.canceled && result.filePaths.length > 0) {
    return result.filePaths;
  }
  
  return [];
});



// 批量处理图片
ipcMain.handle('process-images', async (event, { files, outputFolder, options }) => {
  try {
    // 使用程序运行目录下的image文件夹作为输出目录
    const actualOutputFolder = path.join(process.cwd(), 'image');
    await fs.ensureDir(actualOutputFolder);
    
    const results = [];
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      // 发送进度更新
      event.sender.send('processing-progress', {
        current: i + 1,
        total: files.length,
        fileName: path.basename(file)
      });
      
      try {
        // 不使用前缀和后缀，直接使用原文件名
        const modifiedOptions = {
          ...options,
          prefix: '',
          suffix: ''
        };
        const result = await imageProcessor.processImage(file, actualOutputFolder, modifiedOptions);
        results.push({ file, success: true, outputPath: result, originalPath: file });
      } catch (error) {
        results.push({ file, success: false, error: error.message });
      }
    }
    
    return results;
  } catch (error) {
    throw new Error(`批量处理失败: ${error.message}`);
  }
});

// 替换原文件
ipcMain.handle('replace-original-files', async (event, results) => {
  try {
    const successfulResults = results.filter(r => r.success);
    
    for (const result of successfulResults) {
      try {
        // 将处理后的文件复制回原位置
        await fs.copy(result.outputPath, result.originalPath, { overwrite: true });
      } catch (error) {
        console.error(`替换文件失败 ${result.originalPath}:`, error);
        return { success: false, error: `替换文件失败: ${error.message}` };
      }
    }
    
    // 删除image文件夹中的临时文件
    const imageFolder = path.join(process.cwd(), 'image');
    try {
      await fs.remove(imageFolder);
    } catch (error) {
      console.error('删除临时文件夹失败:', error);
    }
    
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 获取文件夹中的图片文件
async function getImageFilesFromFolder(folderPath) {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp', '.svg', '.ico'];
  const files = [];
  
  try {
    const items = await fs.readdir(folderPath);
    
    for (const item of items) {
      const itemPath = path.join(folderPath, item);
      const stat = await fs.stat(itemPath);
      
      if (stat.isFile()) {
        const ext = path.extname(item).toLowerCase();
        if (imageExtensions.includes(ext)) {
          files.push(itemPath);
        }
      }
    }
  } catch (error) {
    console.error('读取文件夹失败:', error);
  }
  
  return files;
}

// 窗口控制
ipcMain.handle('minimize-app', () => {
  if (mainWindow) {
    mainWindow.minimize();
  }
});

ipcMain.handle('maximize-app', () => {
  if (mainWindow) {
    if (mainWindow.isMaximized()) {
      mainWindow.unmaximize();
    } else {
      mainWindow.maximize();
    }
  }
});

// 关闭应用
ipcMain.handle('close-app', () => {
  app.quit();
});